package net.tv90.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.tv90.business.dao.StudentMapper;
import net.tv90.business.dao.SubjectMapper;
import net.tv90.business.dao.TeacherMapper;
import net.tv90.business.model.Mail;
import net.tv90.business.model.SelectionInfoMail;
import net.tv90.business.model.domain.Student;
import net.tv90.business.model.domain.Subject;
import net.tv90.business.model.domain.Teacher;
import net.tv90.business.model.dto.SubjectQueryDTO;
import net.tv90.business.model.dto.SubjectSubmitDTO;
import net.tv90.business.model.vo.StudentVO;
import net.tv90.business.model.vo.SubjectVO;
import net.tv90.business.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SubjectServiceImpl implements SubjectService {

    @Autowired
    SubjectMapper subjectMapper;

    @Autowired
    TeacherMapper teacherMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;

    @Transactional
    @Override
    public void submitSubject(SubjectSubmitDTO dto) {
        Teacher teacher = teacherMapper.selectById(dto.getTeacherId());
        if (teacher == null) {
            throw new IllegalArgumentException("教师id不存在");
        }
        Integer count = subjectMapper.selectSubjectCountSubmittedByTeacher(dto.getTeacherId());
        if (count >= 5) {
            throw new IllegalArgumentException("课题数已经达到上限5个");
        }
        Subject subject = Subject.builder()
                .name(dto.getName())
                .difficulty(dto.getDifficulty())
                .teacherId(dto.getTeacherId())
                .studentId(null)
                .status(0)
                .selected(0)
                .build();
        subjectMapper.insert(subject);
    }

    @Override
    public List<SubjectVO> querySubject(SubjectQueryDTO dto) {
        //id精确查询
        if (dto.getSubjectId() != null && dto.getSubjectId() != 0) {
            Subject subject = subjectMapper.selectById(dto.getSubjectId());
            if (subject != null) {
                SubjectVO subjectVO = createVOById(subject);
                return Collections.singletonList(subjectVO);
            }
            return null;
        }

        if (dto.getStudentId() != null && dto.getStudentId() != 0) {
            //查询选题记录中某学生选的所有课题id
            List<Long> subjectIdList = subjectMapper.querySubjectIdRecordByStudentId(dto.getStudentId());
            List<SubjectVO> resultVO = new ArrayList<>();
            for (Long id : subjectIdList) {
                Subject subject = subjectMapper.selectById(id);
                if (subject != null) {
                    SubjectVO subjectVO = createVOById(subject);
                    resultVO.add(subjectVO);
                }
            }
            return resultVO;
        }
//
//        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
//        //名称模糊查询
//        if (!StrUtil.isEmpty(dto.getSubjectName())) {
//            subjectQueryWrapper.like("name", dto.getSubjectName());
//        }
//
//        //查询所有/只查询未被选择的课题
//        if (dto.getShowAll() == 0) {
//            subjectQueryWrapper.like("selected", 0);
//        }
//
//        //处理教师姓名
//        if (!StrUtil.isEmpty(dto.getTeacherName())) {
//            QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
//            teacherQueryWrapper.eq("real_name", dto.getTeacherName());
//            List<Teacher> teachers = teacherMapper.selectList(teacherQueryWrapper);
//            subjectQueryWrapper.in("teacher_id", teachers.stream().map(Teacher::getId).toList());
//        }
//
//        //处理排序
//        if (dto.getDesc() == 0) {
//            subjectQueryWrapper.orderByDesc(dto.getOrderBy());
//        } else {
//            subjectQueryWrapper.orderByAsc(dto.getOrderBy());
//        }
//
//        //处理分页
//        IPage<Subject> result = subjectMapper.selectPage(new Page<>(dto.getPage(), dto.getPageSize()), subjectQueryWrapper);
//
//        return result.getRecords();
        List<SubjectVO> vo = subjectMapper.selectByCondition(dto);
        for (SubjectVO subjectVO : vo) {
            List<StudentVO> list = subjectMapper.selectPreSelectionStudentVO(subjectVO.getId());
            subjectVO.setPreStudentName(list);
        }
        System.out.println(vo);
        return vo;
    }

    private SubjectVO createVOById(Subject subject) {
        Student student = studentMapper.selectById(subject.getStudentId());
        Teacher teacher = teacherMapper.selectById(subject.getTeacherId());
        List<StudentVO> list = subjectMapper.selectPreSelectionStudentVO(subject.getId());
        return SubjectVO.builder()
                .id(subject.getId())
                .name(subject.getName())
                .difficulty(subject.getDifficulty())
                .selected(subject.getSelected())
                .status(subject.getStatus())
                .studentName(student == null ? null : student.getRealName())
                .preStudentName(list)
                .teacherName(teacher.getRealName())
                .build();
    }

    @Override
    public List<StudentVO> queryPreSelectionRecord(Long id) {
        if (id == null) {
            return null;
        }
        return subjectMapper.selectPreSelectionStudentVO(id);
    }

    @Transactional
    @Override
    public boolean deleteSubject(Long id, Long teacherId) {
        if (id == null || teacherId == null) {
            return false;
        }
        if (subjectMapper.deleteSubject(id, teacherId) > 0) {
            subjectMapper.deleteSubjectRecord(id);
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public boolean selectSubject(Long id, Long studentId) {
        if (id == null || studentId == null) {
            return false;
        }
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("student_id", studentId);
        if (subjectMapper.exists(subjectQueryWrapper)) {
            throw new IllegalArgumentException("选题失败，你已经被老师选中");
        }
        if (subjectMapper.selectRecordCount(id, studentId) > 0) {
            throw new IllegalArgumentException("不能重复选题");
        }
        if (subjectMapper.selectSubjectCountSelectedByStudent(studentId) >= 2) {
            throw new IllegalArgumentException("选题失败，选题数量已达上限2个");
        }
        Long teacherId = subjectMapper.selectTeacherIdBySubjectId(id);
        Long count;
        if (teacherId != null
                && (count = subjectMapper.checkDuplicateTeacher(id, studentId, teacherId)) != null
                && count != 0) {
            throw new IllegalArgumentException("不能重复选同一名导师");
        }
        subjectMapper.selectSubject(id, studentId, teacherId);
        return true;
    }

    @Transactional
    @Override
    public boolean withdrawSubject(Long id, Long studentId) {
        if (id == null || studentId == null) {
            return false;
        }
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("student_id", studentId);
        if (subjectMapper.exists(subjectQueryWrapper)) {
            throw new IllegalArgumentException("撤销选题失败，你已经被老师选中");
        }
        return subjectMapper.withdrawSubject(id, studentId) > 0;
    }

    @Transactional(isolation = Isolation.SERIALIZABLE)
    @Override
    public boolean confirmSelectStudent(Long id, Long studentId, Long teacherId) {
        if (id == null || studentId == null || teacherId == null) {
            return false;
        }
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("student_id", studentId);
        if (subjectMapper.confirmStudentInRecord(id, studentId, teacherId) >= 0
                && subjectMapper.confirmStudent(id, studentId, teacherId) == 1
        ) {
            subjectMapper.deleteAllRecord(studentId);

            Student student = studentMapper.selectById(studentId);
            String code = student.getCode();
            Teacher teacher = teacherMapper.selectById(teacherId);
            Subject subject = subjectMapper.selectById(id);

            //根据学号code获得用户email和username
            //同步方法，如何查询？HTTP，太慢
            //选择使用RPC框架实现

            SelectionInfoMail infoMail = new SelectionInfoMail("", "",subject.getName(), teacher.getRealName(), teacher.getPhone());
            jmsMessagingTemplate.convertAndSend("queue.selection", infoMail);
            return true;
        }
        return false;
    }

}
